//
//  CPNavViewController.m
//  zent
//
//  Created by Morplcp on 2018/11/7.
//  Copyright © 2018 zentcm. All rights reserved.
//

#import "CPNavViewController.h"
#import "Aspects.h"
#import <objc/runtime.h>

static char CPNavBarKey;
static char CPShowNavBarKey;

@implementation UIViewController (CPNavViewController)

+ (void)load
{
    [UIViewController aspect_hookSelector:@selector(viewDidLoad) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info)
     {
         UIViewController *instance = (UIViewController *)info.instance;
         if (instance.needNavBar)
         {
             instance.cp_navBar = [[CPNavigationBar alloc] init];
             [instance.view addSubview:instance.cp_navBar];
         }
     } error:nil];
    
    [UIViewController aspect_hookSelector:@selector(viewWillLayoutSubviews) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info)
     {
         UIViewController *instance = (UIViewController *)info.instance;
         if (instance.cp_navBar)
         {
             [instance.view bringSubviewToFront:instance.cp_navBar];
         }
     } error:nil];
}

- (void)setCp_navBar:(CPNavigationBar *)cp_navBar
{
    objc_setAssociatedObject(self, &CPNavBarKey, cp_navBar, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (CPNavigationBar *)cp_navBar
{
    return objc_getAssociatedObject(self, &CPNavBarKey);
}

- (void)setNeedNavBar:(BOOL)needNavBar
{
    objc_setAssociatedObject(self, &CPShowNavBarKey, @(needNavBar), OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)needNavBar
{
    return objc_getAssociatedObject(self, &CPShowNavBarKey);
}

@end
